/*
 * litle project to make XML file from *.txt 
 */
package xmlmaker;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Jakub Kaluzka <jkaluzka at gmail.com>
 */
public class XMLMaker {

    /**
     * @param args the command line arguments
     */
    public static void make(String inputFile, String outputFile) throws FileNotFoundException, IOException, ParserConfigurationException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        //root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("root");
        doc.appendChild(rootElement);

        //Prepares to read from the input file.
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
            //scanner = new Scanner(input);
        } catch (Exception e) {
            System.out.println("Input file does not exist or is not readable. Program will exit.\n" + e);
            return;
        }

        //Prepares to write to the output file.
        //PrintWriter writer;
        BufferedWriter writer = null;
        try {
            //writer = new PrintWriter(output);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile)));
            writer.write("<root>");
            writer.newLine();
        } catch (Exception e) {
            System.out.println("Output file location is not writable. Program will exit.\n" + e);
            return;
        }

        boolean firstLine = true;
        long totalLines = 0;
        long processedLines = 0;
        String[] headers = null;

        //Reads in every line of the text file and attempts to convert it into XML elements.
        //while (true){//scanner.hasNext()) {
        for(String line; (line = reader.readLine()) != null;) {
            //String line = reader.readLine();//scanner.nextLine().trim();
            line = line.replaceAll("[\\t]", "");
            String[] elements = line.split("#");

            //If it's the first line, it becomes the header line, and the operation moves on to the next line.  Otherwise, continue as normal.
            if (firstLine) {
                headers = elements.clone();
                firstLine = false;
                continue;
            }
            ++totalLines; //The first line is not counted in totalLines.

            //Skips this line if there aren't enough elements (in regards to the number of headers).
            if (elements.length < headers.length) {
                continue;
            }

            //Prints each element from the text file line as an XML element.
            for (int i = 0; i < headers.length; ++i) {
                writer.write("<" + headers[i].toLowerCase() + ">" + elements[i] + "</" + headers[i].toLowerCase() + ">");
            }

            //Prints an extra line (for readability) after every group of elements.
            writer.newLine();

            ++processedLines;
        }

        //Cleans up and displays confirmation message.
        reader.close();
        writer.write("</root>");
        writer.close();
        System.out.printf(
                "XML file created at %s\n"
                + "%d/%d lines processed.\n",
                outputFile,
                processedLines,
                totalLines);

    }

    private static String convertToFileURL(String fileName) {
        String path = new File(fileName).getAbsolutePath();
        if (File.separatorChar != '/') {
            path = path.replace(File.separatorChar, '/');
        }
        return path;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        String inputFile = null, outputFile = null;

        if (args.length == 1) {
            inputFile = outputFile = convertToFileURL(args[0]);
        } else if (args.length == 2) {
            inputFile = convertToFileURL(args[0]);
            outputFile = convertToFileURL(args[1]);
        } else if (args.length == 0) {
            inputFile = outputFile = "kumiteABCD.txt";
        } else {
            System.out.println("Bledna liczba parametrow");
            System.exit(1);
        }
        outputFile = outputFile.replaceAll(".txt", ".xml");
        System.out.println(outputFile);
        try {
            make(inputFile, outputFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLMaker.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ParserConfigurationException ex) {
            Logger.getLogger(XMLMaker.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
